import 'package:flutter/material.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_color.dart';

import 'config.dart';

/// 描述: ViewModel基类
/// 
/// @Author tangzhentao
///  @CreatedTime 20:07 2022/6/17
/// 

class Viewmodel extends ChangeNotifier {
  /// 错误
  final StateInfo _failure = StateInfo('数据加载失败', Res.imagesPageFailure);
  StateInfo get failure => _failure;

  /// 空数据
  final StateInfo _empty = StateInfo('暂无任何数据', Res.imagesPageEmpty);
  StateInfo get empty => _empty;

  /// 页面状态默认成功
  PageState _state = PageState.success;
  PageState get state => _state;

  /// 成功的内容变化
  int _successChangedCount = 0;
  int get successChangedCount => _successChangedCount;

  /// 背景色
  Color notSuccessColor = XfgColor.transparent;

  /// 设置列表变化
  setSuccessChange() {
    if (_state != PageState.success) _state = PageState.success;
    _successChangedCount++;
    notifyListeners();
  }

  /// 更新状态
  /// [viewState] 页面状态
  /// [rebuild] 是否更新页面，默认true
  setState(PageState pageState, {bool rebuild = true}) {
    _state = pageState;
    if (rebuild) notifyListeners();
  }

  /// 加载中
  setLoading() {
    _state = PageState.loading;
    notifyListeners();
  }

  /// 加载成功
  setSuccess() {
    _state = PageState.success;
    notifyListeners();
  }

  /// 更新错误状态
  /// [msg] 错误信息
  /// [rebuild] 是否更新页面，默认true
  setFailed({String? msg, String? image, bool rebuild = true}) {
    _state = PageState.error;
    if (msg?.isNotEmpty == true) _failure.msg = msg!;
    if (image?.isNotEmpty == true) _failure.image = image!;
    if (rebuild) notifyListeners();
  }

  /// 更新空数据
  /// [msg] 空数据信息
  /// [rebuild] 是否更新页面，默认true
  setEmpty({String? msg, String? image, bool rebuild = true}) {
    _state = PageState.empty;
    if (msg?.isNotEmpty == true) _empty.msg = msg!;
    if (image?.isNotEmpty == true) _empty.image = image!;
    if (rebuild) notifyListeners();
  }

  /// 加载失败重新加载
  onRetry() {}

  /// 获取到空数据点击逻辑
  onReload() {}

  /// 是否已经销毁，默认false
  bool _hasDispose = false;

  /// 隐藏键盘
  void hideKeyboard() { FocusManager.instance.primaryFocus?.unfocus(); }

  @override
  void notifyListeners() {
    if (_hasDispose) return;
    super.notifyListeners();
  }

  @override
  void dispose() {
    _hasDispose = true;
    super.dispose();
  }
}